<template>
  <basic-drawer
    :visible="visible"
    :title="title"
    ok-text="保存配置"
    @ok="handleSubmit"
    @open="handleBeforeOpen"
    @close="handleBeforeClose"
    @cancel="emits('update:visible', false)">
    <a-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      layout="vertical">
      <a-form-item
        field="name"
        label="规则名称"
        hide-asterisk
        asterisk-position="end"
        required>
        <a-input
          v-model="formData.name"
          :max-length="20"
          class="!w-100"
          placeholder="请输入规则名称">
        </a-input>
      </a-form-item>
      <a-form-item
        label="匹配规则"
        hide-asterisk
        asterisk-position="end"
        required>
        <matching-rule-view
          ref="matchingView"
          v-model="ruleGroups"
          class="w-full"></matching-rule-view>
      </a-form-item>
      <a-form-item
        label="配置标头"
        hide-asterisk
        asterisk-position="end"
        required>
        <http-header-view
          ref="httpHeaderViewRef"
          v-model:headers="headers"
          class="w-full"></http-header-view>
      </a-form-item>
      <a-form-item
        v-if="list.length && showPriority"
        field="order"
        label="执行优先级"
        hide-asterisk
        asterisk-position="end"
        required>
        <section class="flex flex-col">
          <a-select
            v-model="formData.order"
            placeholder="请选择执行优先级"
            class="!w-100"
            :options="priorityOptions" />
          <a-form-item
            v-if="formData.order === 2"
            field="priority"
            hide-label
            asterisk-position="end"
            class="!mb-0 mt-2"
            required>
            <a-select
              v-model="formData.priority"
              class="w-[336px]"
              placeholder="优先触发创建的规则，再触发选择的规则">
              <a-option
                v-for="item in list"
                :key="item.id"
                :label="item.name"
                :value="item.priority" />
            </a-select>
          </a-form-item>
          <span v-if="formData.order === 2" class="text-5 text-xs/5"
            >在此规则前执行</span
          >
        </section>
      </a-form-item>
    </a-form>
  </basic-drawer>
</template>
<script lang="ts" setup>
import type { UrlListItem } from '@/apis/model/transform'
import {
  addApiSiteConversionRuleApi,
  getApiSiteConversionRuleApi,
  updateApiSiteConversionRuleApi
} from '@/apis/modules/site/transform'
import type { IMatchingGroup } from '@/components/MatchingRule/types'
import { getFieldValue } from '@/components/MatchingRule/utils'
import { type FieldRule, type FormInstance } from '@arco-design/web-vue'
import { v4 as uuidV4 } from 'uuid'
import HttpHeaderView from './HttpHeaderView/HttpHeaderView.vue'
import type { HeaderRule } from './HttpHeaderView/types'
interface IProps {
  visible: boolean
  list: UrlListItem[]
  record: UrlListItem
  id?: string
  type: number
  showPriority?: boolean
}
const props = withDefaults(defineProps<IProps>(), {
  visible: false,
  showPriority: true,
  list: () => [],
  type: 1
})
interface IEmits {
  (e: 'update:visible', value: boolean): void
  (e: 'refresh'): void
}
const emits = defineEmits<IEmits>()
const title = computed(() => (props?.record?.id ? '编辑规则' : '创建规则'))
const formRef = ref<FormInstance>()
const matchingView = ref()
const formData = ref({
  name: '',
  expression: '',
  expression_template: '',
  order: undefined,
  priority: undefined,
  config: {},
  type: props.type
})
const formRules = computed<{ [key: string]: FieldRule[] }>(() => {
  return {
    name: [
      {
        required: true,
        message: '请输入规则名称'
      },
      { validator: validateTitle }
    ],
    path: [
      {
        required: true,
        validator: (value: string, callback: any) => {
          if (!value) {
            return callback('请配置路径')
          } else if (value.charAt(0) === '/') {
            callback('路径格式错误，不能以/开头')
          } else {
            callback()
          }
        },
        trigger: 'blur'
      }
    ],
    query: [
      {
        required: true,
        validator: (value: string, callback: any) => {
          if (!value) {
            callback('请配置路径')
          } else if (value.charAt(0) === '?') {
            callback('查询格式错误，不能以?开头')
          } else {
            callback()
          }
        },
        trigger: 'blur'
      }
    ],
    order: [
      {
        required: true,
        message: '请选择执行优先级'
      }
    ],
    priority: [
      {
        required: true,
        message: '请选择自定义规则'
      }
    ]
  }
})
const ruleGroups = ref<IMatchingGroup[]>([
  {
    uuid: uuidV4(),
    rules: [
      {
        uuid: uuidV4(),
        field: '',
        operator: '',
        value: '',
        custom_field: ''
      }
    ]
  }
])
const httpHeaderViewRef = ref()
const headers = ref<HeaderRule[]>([
  { uuid: uuidV4(), action: undefined, key: '', value: '' }
])

const handleBeforeOpen = async () => {
  if (props.record) request({ id: props.record.id })
}
const handleBeforeClose = async () => {
  await formRef.value?.resetFields()
  matchingView.value?.reset()
  await httpHeaderViewRef.value?.reset()
  emits('update:visible', false)
}
const { request } = useRequest(getApiSiteConversionRuleApi, {
  success(res) {
    Object.assign(formData.value, res)
    headers.value =
      res.config.map((item) => {
        return { uuid: uuidV4(), ...item, action: item.value ? 1 : 2 }
      }) || []
    ruleGroups.value[0].rules = res.conditions.map((item) => {
      return {
        ...item,
        value:
          getFieldValue(item)!.count > 1 ? item.value : item.value.toString()
      }
    })
    if (props.list.length) {
      if (props.list.length === 1)
        return (formData.value.order = formData.value.priority)
      const priorityArr = props.list.map((item: UrlListItem) => item.priority!)
      const min = Math.min(...priorityArr)
      const max = Math.max(...priorityArr)
      switch (+formData.value.priority!) {
        case min:
          formData.value.order = A_EXECUTION_PRIORITY.FIRST
          break
        case max:
          formData.value.order = A_EXECUTION_PRIORITY.LAST
          break
        default:
          formData.value.order = A_EXECUTION_PRIORITY.CUSTOM
      }
    } else {
      formData.value.order = formData.value.priority
    }
  }
})
async function handleSubmit() {
  const err = await formRef.value?.validate()
  const err1 = await matchingView.value?.validate()
  const err2 = await httpHeaderViewRef.value?.validate()
  if (err || !err1 || err2[0]) return false

  const headerRules = httpHeaderViewRef.value.generate()
  const data: any = {
    ...omitReactive(formData.value, ['expression', 'expression_template'])
      .value,
    conditions: ruleGroups.value[0].rules.map((item) => {
      return {
        ...item,
        value: !Array.isArray(item.value)
          ? item.value
            ? [item.value]
            : []
          : item.value.filter(Boolean)
      }
    }),
    config: headerRules,
    id: props.record ? props.record?.id : undefined,
    site_id: props.record ? undefined : props.id
  }
  if (formData.value?.order === A_EXECUTION_PRIORITY.FIRST) {
    data.priority = 1
  } else if (formData.value?.order === A_EXECUTION_PRIORITY.LAST) {
    data.priority = props.list.length + 1
  } else {
    data.priority = formData?.value?.priority
  }
  const api_path = props.record
    ? updateApiSiteConversionRuleApi
    : addApiSiteConversionRuleApi
  api_path(data).then(() => {
    ToastUtils.success('保存成功')
    emits('update:visible', false)
    emits('refresh')
  })
}
</script>

<style lang="less" scoped></style>
